package com.roy.shardingDemo.algorithm;

import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.*;

public class DatabaseComplexShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    private static final String COLUMN_ID = "id";
    private static final String COLUMN_MEMBER_ID = "member_id";

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ComplexKeysShardingValue<Long> shardingValue) {
        Set<String> result = new HashSet<>();
        Map<String, Collection<Long>> columnShardingValues = shardingValue.getColumnNameAndShardingValuesMap();

        // 获取 id 和 member_id 的值
        Collection<Long> ids = columnShardingValues.getOrDefault(COLUMN_ID, Collections.emptyList());
        Collection<Long> memberIds = columnShardingValues.getOrDefault(COLUMN_MEMBER_ID, Collections.emptyList());

        // 计算分库逻辑
        for (Comparable<?> id : ids) {
            int databaseSuffix = Math.abs(id.hashCode()) % availableTargetNames.size();
            result.add("m" + databaseSuffix);
        }
        for (Comparable<?> memberId : memberIds) {
            int databaseSuffix = Math.abs(memberId.hashCode()) % availableTargetNames.size();
            result.add("m" + databaseSuffix);
        }

        return result.isEmpty() ? availableTargetNames : result;
    }



    @Override
    public String getType() {
        return "DATABASE_COMPLEX";
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}